package com.zhan.utils.model;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

/**
 * @author 白尚兵
 * @date 2019/11/29 10:04
 **/
@Data
public class CustomQuery extends BaseQuery {
    @ApiModelProperty(value = "自定义查询条件")
    private List<QueryColumn> query;

    /**
     * 填充查询条件
     */
    public void fillQuery() {
        Class cls = this.getClass();
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            QueryField annotation = declaredField.getAnnotation(QueryField.class);
            if (annotation == null || annotation.fill()) {
                String name = declaredField.getName();
                Class<?> type = declaredField.getType();
                Object fieldValue = BeanUtil.getFieldValue(this, name);
                if (Objects.nonNull(fieldValue)) {
                    if (String.class.equals(type) && StrUtil.isBlank((String) fieldValue)) {
                        continue;
                    }
                    query.add(new QueryColumn(name, fieldValue));
                }
            }
        }
    }

    public List<QueryColumn> getQuery() {
        if (query == null) {
            query = Lists.newArrayList();
            fillQuery();
        }
        return query;
    }
}
